<?php
class Admin_Model_Menu {
	protected $pages;
	
	public function getMenu() {
		return ($this->loadMenu ());
	}
	
	private function loadMenu() {
		$cfg = Zend_Registry::get ( 'cnf' );
		$dir = $cfg->resources->frontController->moduleDirectory;
		$dir=$dir->toArray();
		$modules = array ();
		
		foreach ( $dir as $d ) {
				$modules [$d] = scandir ( $d );
		}
		
		$pages = array ();
		$AdimMenu = new Zend_Navigation ();
		foreach ( $modules as $dir => $mods ) {
			foreach ( $mods as $module ) {
				$file = $dir . '/' . $module . '/settings/menu.php';
				
				if (file_exists ( $file )) {
					include ($file);
					$this->AddPages ( $menu );
				}
			}
		}
		$filter = new Zen_Filter_ArrayToTree ();
		$filter->setChildren ( 'pages' );
		$filter->setOrder ( 'weight' );
		$pages = $filter->filter ( $this->pages );
		$AdimMenu->setPages ( $pages );
		return $AdimMenu;
	}
	
	private function AddPages($pages, $parent_id = 0) {
		foreach ( $pages as $page ) {
			
			if (isset ( $page ['module'] )) {
				$page ['route'] = 'backend';
				$page ['resource'] = 'mvc:' . $page ['module'] . ':' . $page ['controller'] . ':' . $page ['action'];
			} else {
				$page ['uri'] = '';
			}
			if(!isset($page ['id'])){
				
				
				$page ['id'] = $page ['resource'];
				
			}
			$id=$page['id'];
			
			if (! isset ( $page ['pages'] )) {
				$page ['parent_id'] = $parent_id;
				if (isset ( $this->pages [$id] )) {
					$page = array_merge ( $this->pages [$id], $page );
				}
				$this->pages [$id] = $page;
			
			} else {
				$pages = $page ['pages'];
				unset ( $page ['pages'] );
				$page ['parent_id'] = $parent_id;
				$this->pages [$id] = $page;
				$this->AddPages ( $pages, $id );
			}
		}
	}

}
   